package org.jackdking.delay.domainv1.server.handler;

import com.alibaba.fastjson.JSON;
import io.lettuce.core.resource.Delay;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jackdking.delay.domainv1.delayService.DelayServiceWorker;
import org.jackdking.delay.domainv1.delayService.messagetype.NotifyMessage;
import org.jackdking.delay.domainv1.infrastructure.translator.DelayMessageTranslator;
import org.jackdking.delay.domainv1.protocol.request.DelayMessageRequestPacket;
import org.jackdking.delay.domainv1.protocol.response.AckPacket;
import org.jackdking.delay.domainv1.vo.NotifyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Data
@Component
@ChannelHandler.Sharable
public class DelayMessageHandler  extends SimpleChannelInboundHandler<DelayMessageRequestPacket> {

    @Autowired
    private DelayServiceWorker delayService;

    private static DelayMessageTranslator<String> delayMessageTranslator = new DelayMessageTranslator();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DelayMessageRequestPacket delayMessageRequestPacket) throws Exception {

        log.info("delay api entry params:{}", JSON.toJSONString(delayMessageRequestPacket));
        NotifyVo<String> notifyVo = JSON.parseObject(delayMessageRequestPacket.getContent(), NotifyVo.class);
        NotifyMessage<String> delayMsg = delayMessageTranslator.toUser(notifyVo);
        try {
            delayService.sendDelayMsg(delayMsg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }

        channelHandlerContext.writeAndFlush(new AckPacket());
    }

//    @Override
//    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DelayMessageRequestPacket delayMessageRequestPacket) throws Exception {
//
//
//        log.info("delay api entry params:{}", JSON.toJSONString(textMessageRequestPacket));
//        NotifyMessage<String> delayMsg = delayMessageTranslator.toUser(notifyVo);
//        try {
//            delayService.sendDelayMsg(delayMsg);
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//        }
//
//
//    }
}
